<template>
  <div class="home-container">
    <div class="files-container">
      <el-skeleton :count="5" animated :loading="!loaded">
        <el-table v-if="loaded" :data="filterTableData" style="width: 100%">
          <el-table-column type="selection" width="55" />

          <el-table-column label="名字" width="180">
            <template #default="scope">
              <el-tag
                type="info"
                v-if="scope.row.type != '目录'"
                @click="handleDownload(scope.$index, scope.row)"
                >{{ scope.row.name }}</el-tag
              >
              <el-tag
                v-if="scope.row.type == '目录'"
                style="cursor: pointer"
                @click="openFolder(scope.$index, scope.row)"
                >{{ scope.row.name }}</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column label="创建时间" prop="gmtCreated" width="200" />
          <el-table-column label="大小" width="100">
            <template #default="scope">
              <span
                >{{
                  scope.row.size > 1024
                    ? (scope.row.size / 1024).toFixed(2) + 'MB'
                    : scope.row.size + 'KB'
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="下载次数" prop="downloadCount" width="100" />
          <el-table-column label="类型" prop="type" width="100" />
          <el-table-column align="right">
            <template #header>
              <div class="search">
                <el-button type="small" @click="router.go(0)">首页</el-button>
              </div>

              <div class="search">
                <el-button
                  type="small"
                  @click="prevPage"
                  v-if="cur_fileFolderId != cur_parentFolderId"
                  >上一目录</el-button
                >
              </div>

              <div class="search">
                <el-button type="small" @click="mkdir">新建文件夹</el-button>
              </div>

              <div class="search">
                <el-input
                  v-model="search"
                  size="small"
                  placeholder="搜索文件"
                />
              </div>
            </template>
            <template #default="scope">
              <el-button
                size="small"
                @click="openFolder(scope.$index, scope.row)"
                v-if="scope.row.type == '目录'"
                >打开文件夹
              </el-button>
              <el-button
                size="small"
                @click="handleDownload(scope.$index, scope.row)"
                >下载</el-button
              >
              <el-button
                size="small"
                @click="handleShare(scope.$index, scope.row)"
                >分享</el-button
              >
              <el-button
                size="small"
                @click="handleRename(scope.$index, scope.row)"
                >重命名</el-button
              >
              <!-- <el-button size="small" @click="handleCopy(scope.$index, scope.row)"
              >复制</el-button
            > -->
              <!-- <el-button size="small" @click="handleMove(scope.$index, scope.row)"
              >移动</el-button
            > -->
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-skeleton>
    </div>
  </div>

  <el-dialog v-model="renamePopupVisible" title="重命名" :show-close="false">
    <el-form ref="form" :model="renameFormData">
      <el-form-item label="名字">
        <el-input v-model="renameFormData.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="renamePopupVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRenameForm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="mkdirPopupVisible" title="重命名" :show-close="false">
    <el-form ref="form" :model="mkdirFormData">
      <el-form-item label="名字">
        <el-input v-model="mkdirFormData.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="mkdirPopupVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMkdirForm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router'
import fileCard from '/src/components/FileCard/index.vue'
import { useUserStore } from '/src/store/user'
import { Timer } from '@element-plus/icons-vue'
import { computed, ref } from 'vue'
import { ElTable } from 'element-plus'
import {
  listByUserId,
  downloadById,
  shareById,
  renameFile,
  getNetdisk,
  addFileFolder,
  listFiles,
  getFileFolder,
  deleteFile,
} from '/src/api/netdisk.js'

const route = useRoute()
const router = useRouter()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<File[]>([])
const user = useUserStore()
const loaded = ref(false)
const renamePopupVisible = ref(false)
const clickFileId = ref('')
const renameFormData = ref({ name: '' })
const cur_fileUserId = ref('')
const cur_fileStorageId = ref('')
const cur_fileFolderId = ref('')
const cur_parentFolderId = ref('')
const mkdirPopupVisible = ref(false)
const mkdirFormData = ref({ name: '' })
interface File {
  id: string
  gmtCreated: string
  name: string
  size: string
  downloadCount: string
  type: string
}
let tableData: File[] = [
  {
    id: '1',
    gmtCreated: '1',
    name: '1',
    size: '1',
    downloadCount: '1',
    type: '1',
  },
]
getNetdisk(user.uid).then((data) => {
  cur_fileUserId.value = data.result.fileUserId
  cur_fileStorageId.value = data.result.fileStorageId
  cur_fileFolderId.value = data.result.fileFolderId
  cur_parentFolderId.value = data.result.fileFolderId
})

function handleType(file) {
  console.log(tableData)
  tableData.forEach((file) => {
    // 文件类型筛选
    switch (file.type) {
      case -1:
        file.type = '目录'
        break
    }
  })
}
listByUserId(user.uid).then((data) => {
  console.log(data)
  tableData = data.result.list
  console.log(tableData)
  handleType(tableData)
  loaded.value = true
})

const search = ref('')
let filterTableData = computed(() =>
  tableData.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
)

const toggleSelection = (rows?: File[]) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}

const handleSelectionChange = (val: File[]) => {
  multipleSelection.value = val
}

const handleDownload = (index: number, row: File) => {
  downloadById(row.id)
}

const handleShare = (index: number, row: File) => {
  shareById(row.id).then((res) => {
    console.log(res)
  })
}

const handleRename = (index: number, row: File) => {
  renamePopupVisible.value = true
  clickFileId.value = row.id
}

const handleCopy = (index: number, row: File) => {
  console.log(index, row)
}

const handleMove = (index: number, row: File) => {
  console.log(index, row)
}

const handleDelete = (index: number, row: File) => {
  loaded.value = false
  search.value = ' '
  let newArr = []
  deleteFile(row.id).then((res) => {
    for (let i = 0; i < tableData.length; i++) {
      if (i !== index) {
        newArr.push(tableData[i])
      }
    }
    tableData = newArr
    console.log(res)
    search.value = ''
    loaded.value = true
  })
}

const mkdir = () => {
  mkdirPopupVisible.value = true
}

const prevPage = () => {
  getFileFolder(cur_fileFolderId).then((res) => {
    console.log(res)
  })
}

const openFolder = (index: number, row: File) => {
  loaded.value = false
  cur_parentFolderId.value = cur_fileFolderId.value
  cur_fileFolderId.value = row.id
  listFiles(cur_fileStorageId.value, cur_fileFolderId.value).then((data) => {
    tableData = [...data.result.list]
    handleType(tableData)
    console.log(tableData)
    search.value = ' '
    loaded.value = true
    search.value = ''
  })
}
/**
 * 重命名弹窗
 */

const submitRenameForm = () => {
  let uploadFile = {
    id: clickFileId.value,
    name: renameFormData.value.name,
  }

  renameFile(uploadFile).then((res) => {})
  renamePopupVisible.value = false
}

const submitMkdirForm = () => {
  let fileFolder = {
    name: mkdirFormData.value.name,
    id: cur_fileFolderId.value,
    parentFolderId: cur_fileFolderId.value,
    fileStorageId: cur_fileStorageId.value,
  }

  addFileFolder(fileFolder).then((res) => {
    loaded.value = false
    search.value = ' '
    res.result.size = 0
    res.result.type = '目录'
    console.log(res.result)
    tableData.unshift(res.result)
    search.value = ''
    loaded.value = true
  })
  mkdirPopupVisible.value = false
}
</script>


<style lang="scss" scoped>
.home-container {
  position: relative;
  width: 100%;
  // max-width: 1000px;
  margin: auto;
}

.files-container {
  border-radius: 4px;
}

.search {
  float: right;
  margin-right: 10px;
}
</style>
